package com.meego.common.oembed;

import java.io.InputStream;
import java.io.OutputStream;

import org.codehaus.jackson.map.AnnotationIntrospector;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.xc.JaxbAnnotationIntrospector;

public class OembedJsonParser implements OembedParser {
	private final ObjectMapper objectMapper;
	
	public OembedJsonParser() {
		this.objectMapper = new ObjectMapper();
		final AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
		   
		objectMapper.setDeserializationConfig(objectMapper.getDeserializationConfig().withAnnotationIntrospector(introspector));
		objectMapper.setSerializationConfig(objectMapper.getSerializationConfig().withAnnotationIntrospector(introspector));
	}
	
	@Override
	public OembedResponse unmarshal(InputStream httpResponse) throws OembedException {
		try {			
			return objectMapper.readValue(httpResponse, OembedResponse.class);
		} catch(Exception e) {
			throw new OembedException(e);
		}
	}

	@Override
	public String marshal(OembedResponse oembedResponse) throws OembedException {
		try {
			return objectMapper.writeValueAsString(oembedResponse);
		} catch (Exception e) {
			throw new OembedException(e);
		}
	}

	@Override
	public void marshal(OembedResponse oembedResponse, OutputStream outputStream) throws OembedException {
		try {
			this.objectMapper.writeValue(outputStream, oembedResponse);
		} catch (Exception e) {
			throw new OembedException(e);
		}
	}
}